package me.xhy.java.springboot3.r2dbc.s05one2one.s055converter;

import io.r2dbc.spi.Row;
import me.xhy.java.springboot3.r2dbc.s05one2one.s051entity.S0511Author;
import me.xhy.java.springboot3.r2dbc.s05one2one.s051entity.S0513Book;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

import java.time.Instant;

@ReadingConverter // 读取数据库数据时，将row转换成对象
public class S055BookConverter implements Converter<Row, S0513Book> {

  @Override
  public S0513Book convert(Row source) {
    S0513Book book = new S0513Book();
    book.setId(source.get("id", Long.class));
    book.setTitle(source.get("title", String.class));
    book.setAuthorId(source.get("author_id", Long.class));
    book.setPublisherTime(source.get("publish_time", Instant.class));

    // book 中的 author
    S0511Author author = new S0511Author();
    author.setId(book.getAuthorId());
    author.setName(source.get("name", String.class));

    book.setAuthor(author);

    return book;
  }

  @Override
  public <U> Converter<Row, U> andThen(Converter<? super S0513Book, ? extends U> after) {
    return Converter.super.andThen(after);
  }
}
